#include<iostream>
#include<unistd.h>
#include<assert.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>

using namespace std;

int main()
{
    //cout<<"hello!!!"<<endl;
    // 1.创建管道
    int pipefd[2] = {0};// pipefd[0]:读端，pipefd[1]:写端
    int n = pipe(pipefd);
    assert(n != -1);
    (void)n;

    //cout<< "pipeid[0]: " << pipefd[0] << endl;//3
    //cout<< "pipeid[1]: " << pipefd[1] << endl;//4

    // 2.创建子进程
    pid_t id = fork();
    assert(id != -1);
    if(id == 0)
    {
        //子进程
        // 3.构建单向通信的信道，父进程写入，子进程读取
        // 3.1关闭子进程不需要的fd，写入
        close(pipefd[1]);
        char buffer[1024];
        while (true)
        {
            ssize_t s = read(pipefd[0],buffer,sizeof(buffer)-1);
            if(s > 0)
            {
                buffer[s] = 0;
                cout <<"child get a message["<<getpid()<< "] father#" <<buffer<<endl;
            }
        }
        //close(pipefd[0]);
        exit(0);
    }
    //父进程
    // 3.构建单向通信的信道
    // 3.1关闭父进程不需要的fd，读取
    close(pipefd[0]);
    string message = "我是父进程，我正在给你发消息";
    int count = 0;
    char send_buffer[1024];
    while (true)
    {
        // 3.2 构建一个变化的字符串
        snprintf(send_buffer,sizeof(send_buffer),"%s[%d] : %d",getpid(),message.c_str(),count++);
        // 3.3 写入
        write(pipefd[1],send_buffer,strlen(send_buffer));
        // 3.4 故意sleep
        sleep(1);
    }
    close(pipefd[1]);
    //pid_t ret = waitpid(id,nullptr,0);
    //assert(ret < 0);
    //(void)ret;

    
    return 0;
}